package com.xuning.emperor.upload.controller;


import com.xuning.emperor.base.Result;
import com.xuning.emperor.upload.dto.UploadReqDTO;
import com.xuning.emperor.upload.dto.UploadRespDTO;
import com.xuning.emperor.upload.service.UploadService;
import com.xuning.emperor.upload.utils.Constant;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 本地文件上传下载请求类
 *
 * @author bool
 */
@Log4j2
@RequiredArgsConstructor
@RestController
public class UploadController  {

    private final UploadService uploadService;

    /**
     * 文件上传
     *
     * @param reqDTO
     * @return
     */
    @PostMapping("/api/common/file/upload")
    public Result<UploadRespDTO> upload(@ModelAttribute UploadReqDTO reqDTO) {
        // 上传并返回URL
        UploadRespDTO respDTO = uploadService.upload(reqDTO.getFile());
        return Result.ok(respDTO);
    }

    /**
     * 独立文件下载
     *
     * @param request
     * @param response
     */
    @GetMapping(Constant.FILE_PREFIX + "**")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        uploadService.download(request, response);
    }
}
